import { Card } from "antd";
import React, { forwardRef, useMemo, useState } from "react";

import {
  ScmHorizontalTimeline,
  ScmHorizontalTimelineElement,
  ScmContractTimelineItem,
} from "@core/rc-components/es/ScmHorizontalTimeline";

import { dateFormatBase, orderStatusTypeMap } from "@core/shared";

import { contractApproveTimeLineBusTypeEnum } from "./contractApproveTimeLineBusTypeEnum";
import { IApproveTimeLineProps } from "./useApproveTimeLineQuery";

/**
 * 				业务类型 0-合同签署 1-合同作废 2-合同关闭 3-合同取消关闭
 */

export interface ApproveTimeLineAction {
  /**
   * @declare
   * @returns @declare
   */
  refresh: () => void;
}
export const ApproveTimeLine = forwardRef<
  ApproveTimeLineAction,
  IApproveTimeLineProps
>(({ itemClickHandle, data = [], titleStart = "合同审批" }) => {
  const titleCountMemo = useMemo(() => {
    if (!data) {
      return {
        0: 0,
        1: 0,
        2: 0,
        3: 0,
      };
    }
    return data.reduce((memo, cur) => {
      if (memo[cur.busType]) {
        memo[cur.busType] += 1;
      } else {
        memo[cur.busType] = 1;
      }

      return memo;
    }, {});
  }, [data]);
  // 反过来渲染
  const dataMemo = useMemo(() => {
    if (!data) {
      return [];
    }
    return data.filter((d) => d && d.id).reverse();
  }, [data]);

  const [activeIndex] = useState(0);

  return (
    <Card
      style={{
        marginTop: "24px",
      }}
      title={`${titleStart}(签署 ${titleCountMemo[0] || 0} 次 / 作废 ${
        titleCountMemo[1] || 0
      } 次 / 关闭 ${titleCountMemo[2] || 0} 次 / 取消关闭 ${
        titleCountMemo[3] || 0
      } 次)`}
      id={"contractApprovalTimeLine"}
    >
      <div
        style={{
          height: "170px",
        }}
      >
        <ScmHorizontalTimeline
          onChange={(index) => {
            itemClickHandle && itemClickHandle(dataMemo[index]);
          }}
        >
          {dataMemo.map((cur, index) => {
            const busTypeData =
              contractApproveTimeLineBusTypeEnum[cur.busType] || {};
            // if (!cur.procInstId) {
            //   return <div></div>;
            // }

            return (
              <ScmHorizontalTimelineElement
                active={index == activeIndex}
                key={index}
                date={dateFormatBase(cur.orderTime, "MM-DD")}
              >
                <ScmContractTimelineItem
                  mainTitle={busTypeData.label}
                  status={
                    cur.orderStatus == 4 || cur.approveState == 15
                      ? "error"
                      : ""
                  }
                  statusTitle={orderStatusTypeMap[cur.orderStatus]?.label || ""}
                ></ScmContractTimelineItem>
              </ScmHorizontalTimelineElement>
            );
          })}
        </ScmHorizontalTimeline>
      </div>
    </Card>
  );
});
